//改变遍历过的节点背景颜色
function selNode(element) {
    element.style.backgroundColor = "#888";
}
//清除遍历标记
function delNode(element) {
    element.style.backgroundColor = "";
}
function allClear(thisNode) {
    delNode(thisNode);
    if (thisNode.children[0]) {
        allClear(thisNode.children[0]);
        allClear(thisNode.children[1]);
    }
}
//click调用函数
function clear() {
    var node = document.getElementById("parent");
    allClear(node);
}
//为按钮注册click事件监听器
window.onload = function () {
    document.getElementById("qian").addEventListener("click", qian);
    document.getElementById("zhong").onclick = zhong;
    document.getElementById("hou").onclick = hou;
    document.getElementById("clear").onclick = clear;
}

//前序遍历
function qian(thisNode) {
    var node = document.getElementById("parent");
    arr = new Array();
    var i = 0;
    var time1 = setInterval(function () {
            if (node){
                selNode( node );
                arr.push( node );
                node = node.children[0];
            } else{
                if( arr[0] ){
                    node = arr.pop().children[1];
                }else{
                    clearInterval(time1);
                }
            }
        }, 1000);
}

//中序遍历
function zhong() {
    var node = document.getElementById("parent");
    arr = new Array();
    var time1 = setInterval(function () {
            while (node) {
                arr.push(node); //存储根节点
                node = node.children[0];
            }
            if (arr[0]) { //无左节点时，遍历根节点或右节点
                node = arr.pop();
                selNode(node);
                node = node.children[1]; //经while循环后，若根节点有右节点，右节点入栈
            } else {
                clearInterval(time1);
            }
        }, 1000);
}
//后续遍历
function hou() {
    var node = document.getElementById("parent");
    arr = new Array();
    var nodeLastVisit = null;
    while (node) {
        arr.push(node);
        node = node.children[0];
    }
    var time1 = setInterval(function () {
            if (arr[0]) {
                node = arr.pop();
                if (node.children[1] == null || node.children[1] == nodeLastVisit) { //无右节点或右节点已经遍历时，遍历根节点
                    selNode(node);
                    nodeLastVisit = node;
                } else {
                    arr.push(node); //有右节点且右节点未遍历，遍历右枝
                    node = node.children[1];
                    while (node) {
                        arr.push(node);
                        node = node.children[0];
                    }
                }
            } else {
                clearInterval(time1);
            }
        }, 1000);
}
